package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.BasisListMapper;
import com.indusfo.spc.mapper.BasisMapper;
import com.indusfo.spc.mapper.ProcessFlowMapper;
import com.indusfo.spc.pojo.Basis;
import com.indusfo.spc.pojo.BasisList;
import com.indusfo.spc.pojo.ProcessFlow;
import com.indusfo.spc.service.BasisService;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 类说明:SOP基础资料 业务实现类
 *
 * @author 王辉
 * @version 创建时间：2018年11月29日 上午10:38:35
 */
@Service
public class BasisServiceImpl implements BasisService {
    // 声明日志的静态变量
    private static final Logger logger = LoggerFactory.getLogger(BasisServiceImpl.class);

    // 注入Mapper
    @Autowired
    BasisMapper basisMapper;
    @Autowired
    ProcessFlowMapper processFlowMapper;
    @Autowired
    BasisListMapper basisListMapper;

    // 新增
    @Override
    public JSONObject insertBasis(Basis basis) {
        try {
            if (basis.getlBasisId() != null) {
                throw new ParamsErrorException("新增时不能输入id");
            }
            if (basis.getlDataState() == null) {
                basis.setlDataState(1);
            }

            if (basis.getdLastUploadTime() == null) {
                basis.setdLastUploadTime(new Date());
            }
                    int row = basisMapper.insertSelective(basis);
                    // 根据返回的影响行数判断是否成功
                    if (row == 0) {
                        throw new ModifyFailedException("新增失败!");
                    }
                    return JSONObject.oK("新增成功!");

        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    // 删除,实际为:将状态字段改为2
    @Override
    public JSONObject deleteBasis(List<Integer> lBasisIds, Integer lDataState) {
        try {
            if (lBasisIds.isEmpty()) {
                throw new ParamsErrorException("未传入基础资料ID");
            }
            //级联删除
            if (lDataState.equals(2)) {
                List<Integer> matids = new ArrayList<>();
                for (int i = 0; i < lBasisIds.size(); i++) {
                    Basis basis = new Basis();
                    basis.setlBasisId(lBasisIds.get(i));
                    Integer matid = basisMapper.listBasissForPage(basis).get(0).getlProduct();
                    if (matid != null) {
                        matids.add(matid);
                    }
                }
                basisMapper.deleteBasisList(matids,null);
            }

            // 调用Mapper删除方法
            int row = basisMapper.deleteBasis(lBasisIds, lDataState);
            // 根据返回的影响行数判断是否成功
            String msg = "";
            switch (lDataState) {
                case 1:
                    msg = "启用";
                    break;
                case 2:
                    msg = "删除";
                    break;
                case 3:
                    msg = "停用";
            }

//            if (row == 0) {
//                // 判断传入的数据状态参数lDataState,返回相应信息
//                switch (lDataState) {
//                    case 1:
//                        throw new ModifyFailedException(msg + "失败!");
//                    case 2:
//                        throw new ModifyFailedException(msg + "失败!");
//                    case 3:
//                        throw new ModifyFailedException(msg + "失败!");
//                }
//            }
            return JSONObject.oK(msg + "成功！", row);
        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    // 更新
    @Override
    public JSONObject updateBasis(Basis basis) {
        try {
            if (basis.getlBasisId() == null || basis.getlBasisId() == 0) {
                throw new ParamsErrorException("更新时未输入SOP基础资料id");
            }
            if (basis.getlProduct() == null || basis.getlProduct() == 0) {
                throw new ParamsErrorException("未传入产品ID");
            }
            if (basis.getdLastUploadTime() == null) {
                basis.setdLastUploadTime(new Date());
            }

                int row = basisMapper.updateByPrimaryKeySelective(basis);
                // 根据返回的影响行数判断是否成功
                if (row == 0) {
                    throw new ModifyFailedException("更新失败!");
                }
                return JSONObject.oK("更新成功!");

        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    // 查询
    @Override
    public JSONObject queryBasis(Basis basis) {
        try {
            // 获取一页显示多少行
            Integer pagesize = basis.getPagesize();
            // 获取查询第几页
            Integer pageindex = basis.getPageindex();
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                basis.setIncept(pagesize * (pageindex - 1));
            }
            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法
            // 上传时间
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            List<Basis> listBasissForPage = basisMapper.listBasissForPage(basis);

            for (int i=0;i<listBasissForPage.size();i++) {
                listBasissForPage.get(i).setVcDLastUploadTime(df.format( listBasissForPage.get(i).getdLastUploadTime()));
            }
            // 判断是否查询到数据
            if (listBasissForPage.isEmpty()) {
                return JSONObject.oK("没有查询到数据", listBasissForPage, 0);
            }
            // 查询有多少条数据条数
            if (pagesize != null && pageindex != null) {
                Integer count = basisMapper.countBasis(basis);
                return JSONObject.oK(listBasissForPage, count);
            }
            return JSONObject.oK(listBasissForPage.get(0));
        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    // 校检参数在数据库中不能重复
    @Override
    public JSONObject checkParamsNotRepeat(Basis basis) {
        try {
            // 判断SOP基础资料的产品ID是否传入
            if (basis.getlProduct() == null || basis.getlProduct() == 0) {
                throw new ParamsErrorException("未传入SOP基础资料的产品ID");
            } else {
                Basis basisForCheckProduct = new Basis();
                basisForCheckProduct.setlProduct(basis.getlProduct());
                if (basis.getlBasisId() != null) {
                    // 有SOP基础资料ID为更新操作,调用剔除本条记录是否有重复
                    basisForCheckProduct.setlBasisId(basis.getlBasisId());
                    int row = basisMapper.countParamsNotRepeat(basisForCheckProduct);
                    if (row > 0) {
                        throw new ParamsErrorException("已存在该产品!");
                    }
                } else {
                    // 无SOP基础资料ID为新增操作,调用Mapper查询所有是否有重复
                    int row = basisMapper.countParamsNotRepeat(basisForCheckProduct);
                    if (row > 0) {
                        throw new ParamsErrorException("已存在该产品!");
                    }
                }
                return JSONObject.oK();
            }
        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    @Override
    public JSONObject insertOrUpdateBasis(Basis basis) {
        try {

            if (basis.getlProduct() == null) {
                throw new ParamsErrorException("产品id不能为空");
            }
            if (basis.getlProVer() == null) {
                throw new ParamsErrorException("版本id不能为空");
            }
            if (basis.getlDataState() == null) {
                basis.setlDataState(1);
            }
            if (basis.getlUserId() == null) {
                basis.setlUserId(1);
            }
            if (basis.getdLastUploadTime() == null) {
                basis.setdLastUploadTime(new Date());
            }
            String msg = "";
            List<Basis> basisS = basisMapper.queryBasisByMatId(basis);
            if (basisS.size() == 0) {
                //新增
                basisMapper.insertSelective(basis);
                msg = "新增成功";
            } else {
                basis.setlBasisId(basisS.get(0).getlBasisId());

                //修改\
                basisMapper.updateBasisByBasisIdForNullTime(basis);
                msg = "修改成功";
            }


            //修改操作
            //获取完整树据
            Basis basisAll = new Basis();
            basisAll = basis;
            if (basisAll == null) {
                throw new ParamsErrorException("完整数据为空");
            }


            //生成空的BasisList
            List<BasisList> basisLists = new ArrayList<>();
            //获取当前版本下的工序
            ProcessFlow processFlow = new ProcessFlow();
            processFlow.setlProVer(basis.getlProVer());
            List<ProcessFlow> processFlowList = processFlowMapper.listProcessFlow(processFlow);
            if (processFlowList == null) {
                throw new ParamsErrorException("工序为空");
            }
            for (int i = 0; i < processFlowList.size(); i++) {
                BasisList basisList = new BasisList();
                basisList.setDataState(1);
                basisList.setMatId(basis.getlProduct());
                basisList.setProId(processFlowList.get(i).getlProId());
                basisList.setlProVer(basis.getlProVer());
                basisLists.add(basisList);
            }

            //导入数据
            if (basis.getBasisLists() != null) {
                List<BasisList> basisListss = basis.getBasisLists();
                for (int i = 0; i < basisListss.size(); i++) {
                    for (int j = 0; j < basisLists.size(); j++) {
                        if (basisListss.get(i).getProId().equals(basisLists.get(j).getProId())) {
                            basisLists.get(j).setContent(basisListss.get(i).getContent());
                            basisLists.get(j).setRemark(basisListss.get(i).getRemark());
                            basisLists.get(j).setUpdateTime(basisListss.get(i).getUpdateTime());
                        }
                    }
                }
            }

            //删除源数据
            //级联删除

            List<Integer> matids = new ArrayList<>();
            matids.add(basis.getlProduct());
            basisMapper.deleteBasisList(matids,basis.getlProVer());

            //增加新数据
            for (int i = 0; i < basisLists.size(); i++) {
                if (basisLists.get(i).getContent()!=null) {
                    basisListMapper.insertSelective(basisLists.get(i));
                }
            }


            basisAll.setBasisLists(basisLists);
            return JSONObject.oK(msg, basisAll, basisLists.size());

        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }
}